<script setup>
import { usePostDetailQuery } from '@/composables/usePostDataQuery'
import { useRoute, useRouter } from 'vue-router'
import { ref, watch, onMounted } from 'vue'
import { get, post } from '@/axios/utils/request'
import PostDetailContent from './components/PostDetailContent.vue'
import PostDetailHeader from './components/PostDetailHeader.vue'
import PostDetailReply from './components/PostDetailReply.vue'
import { ElAvatar } from 'element-plus'
import UserAvatar from '@/components/UserAvatar/UserAvatar.vue'
import { formatTime } from '@/utils/transIUtils'
import EmptyExpert from '@/assets/empty-expert.svg'

import '@element-plus/icons-vue'
import { View, ChatRound, Star, Clock, Lock, Unlock } from '@element-plus/icons-vue'


// 模拟版块信息数据
const sectionInfo = ref({
  name: '技术交流',
  postCount: 1234,
  replyCount: 5678,
  moderators: [
    { id: 1, name: '张三', avatar: 'https://placekitten.com/40/40' },
    { id: 2, name: '李四', avatar: 'https://placekitten.com/41/41' }
  ]
})

// 模拟相关帖子数据
const relatedPosts = ref([])

const moderator = ref(null)
const adminList = ref([])

const route = useRoute()
const router = useRouter()

const postId = ref(route.params.id)


const { data: detailData, refetch: refetchDetailData, isError ,error, } = usePostDetailQuery(postId)

const showFullDesc = ref(false)
const descRef = ref(null)
const isDescOverflow = ref(false)

function checkDescOverflow() {
  if (descRef.value) {
    isDescOverflow.value = descRef.value.scrollHeight > descRef.value.offsetHeight + 2
  }
}

watch(() => detailData.value?.result?.topicInfo?.description, () => {
  showFullDesc.value = false
  setTimeout(checkDescOverflow, 50)
})



onMounted(() => {
  setTimeout(checkDescOverflow, 100)
})

// 监听路由变化
watch(route, (newRoute) => {
  postId.value = newRoute.params.id
})

// 获取同主题帖子
async function fetchRelatedPosts() {

  if (!detailData.value?.result?.topicInfo?.id) return
  const params = {
    topicId: detailData.value.result.topicInfo.id,
    page: 1,
    order: 'id desc'
  }
  const res = await post('/post/getListByTopicId', params)

  if (res && res.code === 0 && res.result && Array.isArray(res.result.data)) {
    relatedPosts.value = res.result.data.slice(0, 10)
  } else {
    relatedPosts.value = []
  }
}

// 获取主题详情（版主/管理员）
async function fetchTopicDetail() {
  const topicId = detailData.value?.result?.topicInfo?.id
  if (!topicId) return

  const res = await get('/topic/detail', { id: topicId })

  if (res && res.code === 0 && res.result) {
    moderator.value = res.result.userInfo
    adminList.value = Array.isArray(res.result.adminList) ? res.result.adminList : []
  } else {
    moderator.value = null
    adminList.value = []
  }
}

watch(() => detailData.value?.result?.topicInfo?.id, (id) => {
  if (id) {
    fetchRelatedPosts()
    fetchTopicDetail()
  }
})
onMounted(() => {
  if (detailData.value?.result?.topicInfo?.id) {
    fetchRelatedPosts()
    fetchTopicDetail()
  }
})
const fetchDetailData = () => {
  console.log('refresh2')
  // fetchRelatedPosts()
  // fetchTopicDetail()
  refetchDetailData()
}

const goToRelatedPost = (id) => {
  if (!id) return
  // 跳转到对应帖子详情
  router.push(`/home/post/${id}`)
}

const goToTopic = (id) => {
  if (!id) return
  router.push(`/topic/${id}`)
}

</script>

<template>
  <!-- <div
    class="bg-[--surface-0] rounded-tl-lg rounded-bl-lg overflow-hidden flex flex-col relative h-full"
    v-if="detailData"> -->
  <div
    class="bg-[--surface-0] rounded-tl-lg rounded-bl-lg overflow-hidden flex  relative h-full w-[80%]  max-w-[1600px] mx-auto"
    v-if="detailData">
    <div class="left-content">
      <PostDetailHeader :title="detailData.result.title" :postId="postId" :topicId="detailData.result.topicId"
        :isAdmin="detailData.result.isAdmin" :uid="detailData.result.userInfo.uid" :postInnerTop="detailData.result.postInnerTop" />
      <PostDetailContent :data="detailData.result" :postId="postId" @refresh="fetchDetailData" />
      
        <PostDetailReply v-if="detailData.result.topicInfo.postDisplayStyle !=2" :postId="detailData.result.id" @refresh="fetchDetailData" />

    </div>
    <div class="right-content">
      <!-- 版块信息卡片 -->
      <div class="section-card">
        <div class="bg-cover bg-center rounded-t-lg"
          :style="{ backgroundImage: `url(${detailData?.result.topicInfo.bgImage})`, width: '100%', height: '100px' }">
        </div>
        <h3 class="section-title flex items-center gap-2">
          <!-- <UserAvatar :avatar="detailData.result.topicInfo?.coverImage"   /> -->
          <img :src="detailData.result.topicInfo?.coverImage" alt=""
            class="w-8 h-8 object-cover rounded-full cursor-pointer"
            @click="goToTopic(detailData.result.topicInfo.id)" />

          {{ detailData.result.topicInfo.topicName }}
        </h3>
        <div class="desc-wrapper relative">
          <div ref="descRef" :class="['topic-desc', { 'desc-ellipsis': !showFullDesc }]">
            {{ detailData.result.topicInfo.description }}
          </div>
          <div v-if="isDescOverflow && !showFullDesc" class="show-more-btn" @click="showFullDesc = true">显示更多</div>
          <div v-if="showFullDesc && isDescOverflow" class="show-more-btn" @click="showFullDesc = false">收起</div>
          <div class="text-sm text-[--text-2] flex items-center gap-1">
            <el-icon class="text-blue-400">
              <Clock />
            </el-icon>
            创建于{{ formatTime(detailData.result.topicInfo.createTime) }}
          </div>
          <div class="text-sm text-[--text-2] flex items-center gap-1">
            <el-icon :class="detailData.result.topicInfo.isPrivacy ? 'text-orange-400' : 'text-green-500'">
              <component :is="detailData.result.topicInfo.isPrivacy ? Lock : Unlock" />
            </el-icon>
            {{ detailData.result.topicInfo.isPrivacy ? '隐私' : '公开' }}
          </div>
        </div>

        <div class="section-stats">
          <div class="stat-item">
            <span class="stat-label">帖子数</span>
            <span class="stat-value">{{ detailData?.result.topicInfo.postCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">成员数</span>
            <span class="stat-value">{{ detailData?.result.topicInfo.userCount }}</span>
          </div>
        </div>
        <div class="moderators">
          <h4 class="moderators-title">主题版主</h4>
          <div class="moderators-list">
            <div v-if="moderator" class="moderator-item moderator-leader">
              <el-avatar :src="moderator.avatar" :size="28" />
              <span class="moderator-name font-bold text-blue-700">{{ moderator.username }}</span>
              <span class="moderator-label">(主题版主)</span>
            </div>
          </div>
          <template v-if="adminList.length">
            <h4 class="moderators-title mt-3">管理员</h4>
            <div class="moderators-list">
              <div v-for="admin in adminList" :key="admin.uid" class="moderator-item">
                <el-avatar :src="admin.avatar" :size="24" />
                <span class="moderator-name">{{ admin.username }}</span>
                <span class="moderator-label">(管理员)</span>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 相关帖子列表 -->
      <div class="related-posts">
        <h3 class="related-title">同主题其他帖子</h3>
        <div class="post-list">
          <div v-if="relatedPosts.length === 0" class="flex flex-col items-center justify-center py-10 text-slate-400">
            <img :src="EmptyExpert" alt="暂无帖子" class="w-20 h-20 mb-2 opacity-80" />
            <div class="text-lg font-semibold">暂无其他帖子</div>
          </div>
          <div v-else>
            <div v-for="post in relatedPosts" :key="post.id"
              class="post-item cursor-pointer hover:bg-blue-50 transition rounded-lg px-2 -mx-2"
              @click="goToRelatedPost(post.id)">
              <div class="post-author">
                <el-avatar :src="post.userInfo?.avatar" :size="24" />
                <span class="author-name">{{ post.userInfo?.username }}</span>
              </div>
              <div class="post-title" :title="post.title">{{ post.title }}</div>
              <div class="post-meta">
                <span class="meta-item">
                  <el-icon>
                    <View />
                  </el-icon>
                  {{ post.readCount }}
                </span>
                <span class="meta-item">
                  <el-icon>
                    <ChatRound />
                  </el-icon>
                  {{ post.commentCount }}
                </span>
                <span class="meta-item">
                  <el-icon>
                    <Star />
                  </el-icon>
                  {{ post.fabulousCount }}
                </span>
                <span class="meta-date">{{ formatTime(post.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="mt-64" v-else> 
          <div class="flex flex-col items-center justify-center">
            <img src="/src/assets/empty-expert.svg" class="w-24 h-24 text-gray-400" alt="禁用图片" />
            <p class="mt-4 text-gray-500 text-lg">暂无数据</p>
          </div>
        </div>
</template>

<style scoped lang="scss">
.right-content {
  width: 300px;
  margin-left: 20px;
  flex-shrink: 0;
  overflow: auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.section-card {
  background: #fff;
  border-radius: 10px;
  padding: 18px 18px 14px 18px;
  margin-bottom: 0;
  box-shadow: 0 2px 12px 0 rgba(56, 112, 255, 0.06);
  border: 1.5px solid #e6eaf2;
  position: relative;
  margin-top: 2px;
}

.section-card::after {
  content: '';
  display: block;
  height: 1px;
  background: linear-gradient(90deg, #e6eaf2 0%, #fff 100%);
  position: absolute;
  left: 18px;
  right: 18px;
  bottom: 0;
  opacity: 0.7;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #1a1a1a;
}

.section-stats {
  display: flex;
  margin-bottom: 16px;
  gap: 16px;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-label {
  font-size: 13px;
  color: #8590a6;
  display: block;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.moderators-title {
  font-size: 14px;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.moderators-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 4px;
}

.moderator-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f6f8fa;
  border-radius: 16px;
  padding: 4px 14px 4px 8px;
  box-shadow: 0 1px 3px rgba(56, 112, 255, 0.04);
  font-size: 14px;
}

.moderator-leader {
  background: linear-gradient(90deg, #e3f0ff 0%, #fafdff 100%);
  border: 1.5px solid #a3c8fa;
}

.moderator-label {
  font-size: 12px;
  color: #1765ad;
  margin-left: 2px;
}

.moderator-name {
  font-size: 13px;
  color: #444;
}

.related-posts {
  background: #fff;
  border-radius: 10px;
  padding: 18px 18px 10px 18px;
  box-shadow: 0 2px 12px 0 rgba(56, 112, 255, 0.06);
  border: 1.5px solid #e6eaf2;
  position: relative;
}

.related-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #1a1a1a;
  border-bottom: 1px solid #e6eaf2;
  padding-bottom: 8px;
  margin-left: -2px;
  margin-right: -2px;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f2f7;
  background: transparent;
  transition: background 0.18s;
}

.post-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.post-item:hover {
  background: #fafdff;
  border-radius: 8px;
}

.post-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 13px;
  color: #444;
}

.post-title {
  font-size: 14px;
  color: #1a1a1a;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  cursor: pointer;
  font-weight: 500;
}

.post-title:hover {
  color: #1765ad;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 12px;
  color: #8590a6;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-date {
  margin-left: auto;
}

.desc-wrapper {
  position: relative;
  margin-bottom: 8px;
}

.topic-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.7;
  transition: max-height 0.2s;
  word-break: break-all;
}

.desc-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 4.9em;
}

.show-more-btn {
  color: #1765ad;
  font-size: 13px;
  cursor: pointer;
  margin-top: 2px;
  display: inline-block;
  background: #fafdff;
  border-radius: 8px;
  padding: 2px 12px;
  margin-left: -8px;
  margin-bottom: 2px;
  box-shadow: 0 1px 4px 0 rgba(56, 112, 255, 0.06);
  transition: background 0.18s, color 0.18s;
}

.show-more-btn:hover {
  background: #e6f0fa;
  color: #145399;
}
</style>
